package com.example.shootinggamebackend.utils;

import com.example.shootinggamebackend.dao.FeedBackDao;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

@Component
public class initDB {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    FeedBackDao feedBackDao;


    @PostConstruct
    void init() {
        initMysql();
    }


    // 初始化数据库
    void initMysql() {
        try {
            // 创建数据库和表
            Path initSqlPath = Path.of("src/main/resources/data/sql/initMysql.sql");
            if (Files.exists(initSqlPath)) {
                String sql = Files.readString(initSqlPath);
                for (String statement : sql.split(";")) {
                    if (!statement.trim().isEmpty()) {
                        jdbcTemplate.execute(statement.trim());
                    }
                }
            }

            // 载入数据
            int count = feedBackDao.getAllFeedBack().size();
            if (count == 0) {
                loadFeedbackData();
            }

        } catch (IOException e) {
            throw new RuntimeException("初始化数据库失败", e);
        }
    }

    // 从 resources/data/feedback 目录加载数据
    private void loadFeedbackData() throws IOException {
        String[] fileNames = {"prizelet.txt", "jackpot.txt", "obstacle.txt"};
        String[] kinds = {"小奖", "大奖", "障碍物"};
        for (int i = 0; i < fileNames.length; i++) {
            Path filePath = Path.of("src/main/resources/data/feedback", fileNames[i]);
            if (Files.exists(filePath)) {
                List<String> lines = Files.readAllLines(filePath);
                for (String line : lines) {
                    feedBackDao.insertFeedBack(line,kinds[i]);
                }
            }
        }
    }

}
